package com.mew.lobby.net;

import com.mew.common.config.IPSourceProperties;
import com.mew.common.config.SpringContextBean;
import com.zebra.common.TmsServerType;
import com.zebra.remoting.IpInfoProperties;
import com.zebra.remoting.config.TmsServerInfo;
import com.zebra.remoting.protocol.CommandCode;
import com.zebra.remoting.tms.TmsServerApplication;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Set;


@Component
@Order(1)
@Slf4j
public class StartInitialize implements ApplicationRunner {

    @Autowired
    private TmsServerApplication tmsServerApplication;
    @Autowired
    private IPSourceProperties ipSourceProperties;
//    @Autowired
//    private AucRedisService aucRedisService;

    @Value("${log.lv}")
    private String logLV;

    public void start() throws Exception {
//        if (StringUtils.isLegal(logLV)){
//            return;
//        }

//        offline();
        InitializeHandlerMapping.initializeMapping();
        checkCmdHandlerMapping();
        TmsServerInfo lobbyServer = new TmsServerInfo();
        lobbyServer.setTmsType(TmsServerType.LOBBY.code());
        lobbyServer.setGameIds("0,");
        lobbyServer.setVfxs("LOBBY,");

        IpInfoProperties properties = IpInfoProperties.builder()
                .ipOut(ipSourceProperties.getIpOut())
                .ipIn(ipSourceProperties.getIpIn())
                .build();

        tmsServerApplication.run(properties, LobbyHandlerMapCmdType.getMap(), SpringContextBean.getBean(ConnectionHandlerService.class), new LobbyOnlineNumberService(), lobbyServer);
    }

    public void checkCmdHandlerMapping()throws  Exception {
        Map<Integer, CommandCode> cmdMap = LobbyHandlerMapCmdType.getMap();
        Set<Integer> keys = cmdMap.keySet();
        for (Integer k : keys){
            if (InitializeHandlerMapping.getMapping(k) == null){
                throw new Exception("MewHandler <-> CMD is null CMD :" + k);
            }
        }
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        start();
    }
//
//    public void offline(){
//        List<Integer> list = new ArrayList<>(1);
//        list.add(0);
//        List<MewSession> sessions = aucRedisService.findOnlineByGid(list);
//        if (null == sessions || sessions.isEmpty()){
//            return;
//        }
//        sessions.forEach(ses -> aucRedisService.offlineSession(ses.uid));
//    }
}
